package org.john.springbootadmin.module.service.system.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.john.springbootadmin.module.dao.system.SysUserDao;
import org.john.springbootadmin.module.entity.system.SysUser;
import org.john.springbootadmin.module.service.system.SysUserRoleService;
import org.john.springbootadmin.module.service.system.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.design.framework.base.service.impl.BaseServiceImpl;

/**
 * 系统用户管理
 * 
 * @author johnDeng
 * @dateTime 2019-03-18 11:49:44
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Integer> implements SysUserService {
	@Resource
	private SysUserDao sysUserDao;
	@Resource
	private SysUserRoleService sysUserRoleService;

	@PostConstruct
	public void initialize() {
		super.setBaseDao(sysUserDao);
	}

	@Override
	public SysUser login(SysUser user) {

		return sysUserDao.login(user);
	}

	@Override
	public SysUser findById(Integer id) {
		SysUser user = sysUserDao.findById(id);
		List<Integer> role = sysUserRoleService.getRolesByUserId(id);
		user.setRole(role == null ? new ArrayList<Integer>() : role);
		return user;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int deleteBatchById(List<SysUser> list) {
		if (CollectionUtils.isNotEmpty(list)) {
			sysUserRoleService.deleteBatchByUserIds(list);
		}
		return sysUserDao.deleteBatchById(list);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int update(SysUser entity) {
		if (CollectionUtils.isNotEmpty(entity.getRole())) {
			// 先删除关联表，后添加添加关联表
			sysUserRoleService.deleteBatchByUserIds(Arrays.asList(entity));
			sysUserRoleService.addSysUserRole(entity.getRole(), entity.getId());
		}
		return sysUserDao.update(entity);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int insert(SysUser entity) {
		sysUserDao.insert(entity);
		sysUserRoleService.addSysUserRole(entity.getRole(), entity.getId());
		return 1;
	}

	@Override
	public boolean existPhone(String phone) {
		SysUser entity = new SysUser();
		entity.setMobilePhone(phone);
		List<SysUser> list = sysUserDao.getList(entity);
		if (CollectionUtils.isNotEmpty(list)) {
			return true;
		}
		return false;
	}

	@Override
	public SysUser findByPhone(String phone) {
		SysUser entity = new SysUser();
		entity.setMobilePhone(phone);
		return sysUserDao.get(entity);
	}
}
